//
//  MALoginViewController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/7/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MALoginViewController.h"
#import "MARegisterForgetController.h"

#import <CommonCrypto/CommonDigest.h>
#import "JPUSHService.h"

#define NAVBAR_TRANSLATION_POINT 0
#define NavBarHeight 44
@interface MALoginViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UITextField *usernameTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
/** userinfo */
@property(nonatomic,strong) MAUserInfo *userinfo;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTopCons;
@end

@implementation MALoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (IS_IPHONE_5) {
        self.logoTopCons.constant = 30;
        self.title = @"登录";
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupBasic];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10 * kScale, 30 * kScale, 60 * kScale, 40 * kScale);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButtonActionWithSender:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:PROJECT_DEFAULT_COLOR forState:UIControlStateNormal];
    [self.view addSubview:button];
}

- (void)backButtonActionWithSender:(UIButton *)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginButtonClick" object:nil];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)setupBasic {
    self.loginBtn.layer.cornerRadius = 4;
    self.loginBtn.layer.masksToBounds = YES;
    
    self.usernameTF.layer.borderColor = [UIColor whiteColor].CGColor;
    self.pwdTF.layer.borderColor = [UIColor whiteColor].CGColor;
    [self wr_setNavBarTintColor:[UIColor clearColor]];
    
    self.navigationItem.leftBarButtonItem = nil;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (IS_IPHONE_5) {
//        [self.navigationController.navigationBar wr_setTranslationY:0];
    } else {
        [self setNavigationBarTransformProgress:0];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (IS_IPHONE_5) {
//        [self.navigationController.navigationBar wr_setTranslationY:-110];
    } else {
        [self setNavigationBarTransformProgress:1];
    }
    [self hiddenTabbar:YES];
}

- (void)setNavigationBarTransformProgress:(CGFloat)progress
{
    [self.navigationController.navigationBar wr_setTranslationY:(-NavBarHeight * progress)];
    // 有系统的返回按钮，所以 hasSystemBackIndicator = YES
    [self.navigationController.navigationBar wr_setBarButtonItemsAlpha:(1 - progress) hasSystemBackIndicator:NO];
}
- (IBAction)login {
    [self.view endEditing:YES];
    NSString *username = self.usernameTF.text;
    NSString *pwd = self.pwdTF.text;
    if (!username.length || !pwd.length) {
        [MBManager showBriefAlert:@"用户名或密码不能为空"];
        return;
    }
    NSString *md5Pwd = [[self md5:pwd] uppercaseString];
    [MBManager showLoading];
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@?username=%@&password=%@",LOGIN_CHECK,username,pwd];
        request.methodType = ZBMethodTypeGET;
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager showBriefAlert:dataDict[@"message"]];
            NSDictionary *dic = dataDict[@"value"][@"user"][0];
            MAUserInfo *userinfo = [MAUserInfo mj_objectWithKeyValues:dic];
            [MAUserInfoTool saveUserInfo:userinfo];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kMALoginSuccessedNotification object:nil];
            [self takeJiguangTagWithId:[MAUserInfoTool userinfo].ID];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)takeJiguangTagWithId:(NSString *)userid
{
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
    {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",JIGUANG_TAG,userid];
        request.methodType = ZBMethodTypeGET;
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type)
    {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1)
        {
            // 请求成功
            NSMutableArray * tagArray = [NSMutableArray array];
            NSArray * array = dataDict[@"value"];
            if (array.count == 0)
            {
                return;
            }
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
            {
                NSDictionary * dict = obj;
                [tagArray addObject:dict[@"tag"]];
            }];
            //清除tag值
            [JPUSHService setTags:[NSSet setWithArray:tagArray] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq)
             {
                 DLog(@"%tu,%@,%tu",iResCode,iTags,seq);
             } seq:0];
        }
        else
        {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)registerBtnDidClick {
    MARegisterForgetController *vc = [[MARegisterForgetController alloc] init];
    vc.title = @"用户注册";
    vc.isRegister = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)forgetBtnDidClick {
    MARegisterForgetController *vc = [[MARegisterForgetController alloc] init];
    vc.title = @"忘记密码";
    vc.isRegister = NO;
    [self.navigationController pushViewController:vc animated:YES];
}


- (NSString *) md5:(NSString *) input {
    
    const char *cStr = [input UTF8String];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
    
}

@end
